package com.shuai.baibi.config;

import org.elasticsearch.common.util.concurrent.EsAbortPolicy;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;

@Configuration
public class ThreadPoolExecutorConfig {
    private static final int CORE_POOL_SIZE = 2;  // 核心线程数
    private static final int MAXIMUM_POOL_SIZE = 4;   // 最大线程数
    private static final long KEEP_ALIVE_TIME = 10;   // 非核心线程数存活时间
    private static final TimeUnit TIMEUNIT = TimeUnit.SECONDS;   // 非核心线程数存活时间单位
    private static final ArrayBlockingQueue<Runnable> ARRAY_BLOCKING_QUEUE = new ArrayBlockingQueue<>(20);   // 阻塞队列
    private static final RejectedExecutionHandler REJECTED_EXECUTION_HANDLER = new EsAbortPolicy(); // 阻塞队列满后的拒绝策略

    // 线程创建是经过的线程池工厂
    private static final ThreadFactory THREAD_FACTORY = new ThreadFactory() {

        private int threadNum = 1;

        @Override
        public Thread newThread(@NotNull Runnable r) {
            Thread thread = new Thread(r);
            thread.setName("线程-" + threadNum);
            threadNum++;
            return thread;
        }
    };


    @Bean
    public ThreadPoolExecutor threadPoolExecutor() {
        return new ThreadPoolExecutor(CORE_POOL_SIZE,
                MAXIMUM_POOL_SIZE,
                KEEP_ALIVE_TIME,
                TIMEUNIT,
                ARRAY_BLOCKING_QUEUE,
                THREAD_FACTORY,
                REJECTED_EXECUTION_HANDLER);
    }
}
